package com.mw.util;

//从内容中提取第一张图片作为预览图，获取所有<p>中的内容做预览

import com.mw.domain.News;

import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 预览图文工具
 */
public class PreviewDeal {

    public List<News> Deal(List<News> newsList){
        for(int i=0;i<newsList.size();i++){
            //Pattern imgPattern = Pattern.compile("(<img.*?\"(>| />))");
            Pattern imgPattern = Pattern.compile("(<img[^<]*(gif|jpeg|png|jpg|bmp).*?(>|/>))");
            Matcher imgMatcher = imgPattern.matcher(newsList.get(i).getContext());
            if(imgMatcher.find()){
                newsList.get(i).setImg(imgMatcher.group(1));
            }else {
                newsList.get(i).setImg("<img src=\"/image/logo.png\"/>");
            }
            Pattern prePattern = Pattern.compile("(?<=<p>)(.*?)(?=</p>)");
            Matcher preMatcher = prePattern.matcher(newsList.get(i).getContext());
            if(preMatcher.find()){
                newsList.get(i).setPreview(preMatcher.group());
            }else {
                newsList.get(i).setPreview("点击查看详情。");
            }
        }
        return newsList;
    }
}
